#include <stdio.h>
#include <sys/types.h>  
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
  #include <sys/types.h>
  #include <signal.h>
 
int main(int argc, const char *argv[])
{
	int sockfd,acceptfd;
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd < 0)
	{
		perror("socket err.");
		return -1;
	}
	printf("socket ok.\n");
	struct sockaddr_in clientaddr;
	struct sockaddr_in serveraddr;
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);

	socklen_t len=sizeof(clientaddr); 

	if(bind(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0)
	{
		perror("bind err.");
		return -1;
	}
	printf("bind ok.\n");

	if(listen(sockfd,5) < 0)
	{
		perror("listen err.");
		return -1;
	}
	char buf[64];
	ssize_t recvbyte;
	pid_t pid;
	while(1)
	{
        acceptfd=accept(sockfd,(struct sockaddr *)&clientaddr,&len);
		if(acceptfd < 0)
		{
			perror("accept err.");
			return -1;
		}
		printf("client.ip=%s,port:%d\n",(char *)inet_ntoa(clientaddr.sin_addr.s_addr)\
				,ntohs(clientaddr.sin_port));
		printf("accept ok.\n");
		pid=fork();
		if(pid <0)
		{
			perror("fork err.");
			return -1;
		}
		else if(pid==0)
		{ 
			while(1)
			{
				fgets(buf,64,stdin);
				if(buf[strlen(buf)-1] == '\n')
					buf[strlen(buf)-1]='\0';
				send(acceptfd,buf,sizeof(buf),0);
			}
		}
		else{
			while(1)
			{
				memset(buf,0,64);
				recvbyte=recv(acceptfd,buf,64,0);
				if(recvbyte < 0)
				{
					perror("recv err.");
				}else if(recvbyte == 0)
				{
					printf("client exit.\n");
					break;
				}else
				{
					printf("buf:%s\n",buf);
				}

			}
			kill(pid,SIGKILL);
			wait(NULL);
		}
		close(acceptfd);
	}

   close(sockfd);
	return 0;
}
